from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.core.paginator import Paginator
from django.db.models import Q
from django.utils import timezone
from datetime import timedelta
from .models import Book, Category, BorrowRecord, Reservation
from .forms import BookSearchForm, BorrowForm

def book_list(request):
    """书籍列表页面"""
    books = Book.objects.all().select_related('category')
    categories = Category.objects.all()
    
    # 搜索功能
    search_form = BookSearchForm(request.GET)
    if search_form.is_valid():
        query = search_form.cleaned_data.get('query')
        category = search_form.cleaned_data.get('category')
        status = search_form.cleaned_data.get('status')
        
        if query:
            books = books.filter(
                Q(title__icontains=query) |
                Q(author__icontains=query) |
                Q(isbn__icontains=query) |
                Q(publisher__icontains=query)
            )
        
        if category:
            books = books.filter(category=category)
        
        if status:
            books = books.filter(status=status)
    
    # 分页
    paginator = Paginator(books, 12)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'categories': categories,
        'search_form': search_form,
    }
    return render(request, 'books/book_list.html', context)

def book_detail(request, book_id):
    """书籍详情页面"""
    book = get_object_or_404(Book, id=book_id)
    borrow_records = BorrowRecord.objects.filter(book=book).select_related('borrower')[:5]
    
    context = {
        'book': book,
        'borrow_records': borrow_records,
    }
    return render(request, 'books/book_detail.html', context)

@login_required
def borrow_book(request, book_id):
    """借阅书籍"""
    book = get_object_or_404(Book, id=book_id)
    
    if request.method == 'POST':
        form = BorrowForm(request.POST)
        if form.is_valid():
            # 检查书籍是否可借
            if book.available_copies > 0:
                # 创建借阅记录
                borrow_record = BorrowRecord.objects.create(
                    book=book,
                    borrower=request.user,
                    due_date=form.cleaned_data['due_date'],
                    notes=form.cleaned_data['notes']
                )
                
                # 更新书籍状态
                if book.available_copies == book.total_copies:
                    book.status = 'borrowed'
                book.available_copies -= 1
                book.save()
                
                messages.success(request, f'成功借阅《{book.title}》')
                return redirect('book_detail', book_id=book.id)
            else:
                messages.error(request, '该书籍已无可借数量')
    else:
        # 默认还书日期为30天后
        default_due_date = timezone.now() + timedelta(days=30)
        form = BorrowForm(initial={'due_date': default_due_date})
    
    context = {
        'book': book,
        'form': form,
    }
    return render(request, 'books/borrow_book.html', context)

@login_required
def return_book(request, record_id):
    """归还书籍"""
    borrow_record = get_object_or_404(BorrowRecord, id=record_id, borrower=request.user)
    
    if borrow_record.status == 'borrowed':
        # 更新借阅记录
        borrow_record.status = 'returned'
        borrow_record.return_date = timezone.now()
        borrow_record.save()
        
        # 更新书籍状态
        book = borrow_record.book
        book.available_copies += 1
        if book.available_copies == book.total_copies:
            book.status = 'available'
        book.save()
        
        messages.success(request, f'成功归还《{book.title}》')
    else:
        messages.error(request, '该记录状态异常')
    
    return redirect('my_borrows')

@login_required
def my_borrows(request):
    """我的借阅记录"""
    borrow_records = BorrowRecord.objects.filter(borrower=request.user).select_related('book')
    
    context = {
        'borrow_records': borrow_records,
    }
    return render(request, 'books/my_borrows.html', context)

@login_required
def reserve_book(request, book_id):
    """预约书籍"""
    book = get_object_or_404(Book, id=book_id)
    
    # 检查是否已经预约过
    existing_reservation = Reservation.objects.filter(
        book=book, 
        user=request.user, 
        status='pending'
    ).first()
    
    if existing_reservation:
        messages.error(request, '您已经预约过这本书了')
        return redirect('book_detail', book_id=book.id)
    
    # 创建预约记录
    Reservation.objects.create(
        book=book,
        user=request.user
    )
    
    messages.success(request, f'成功预约《{book.title}》')
    return redirect('book_detail', book_id=book.id)

@login_required
def my_reservations(request):
    """我的预约记录"""
    reservations = Reservation.objects.filter(user=request.user).select_related('book')
    
    context = {
        'reservations': reservations,
    }
    return render(request, 'books/my_reservations.html', context)

def category_books(request, category_id):
    """分类书籍列表"""
    category = get_object_or_404(Category, id=category_id)
    books = Book.objects.filter(category=category).select_related('category')
    
    # 分页
    paginator = Paginator(books, 12)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'category': category,
        'page_obj': page_obj,
    }
    return render(request, 'books/category_books.html', context)
